package gson.gson.cclass;

import com.google.gson.JsonElement;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;

import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

public class TypeAdapterExample<T> {
    private final TypeAdapter<T> typeAdapter;

    // 构造方法：接收 TypeAdapter 实例
    public TypeAdapterExample(TypeAdapter<T> typeAdapter) {
        this.typeAdapter = typeAdapter;
    }

    // 从 JSON 字符串解析对象
    public T fromJson(String json) throws IOException {
        return typeAdapter.fromJson(json);
    }

    // 从 JSON Reader 解析对象
    public T fromJson(Reader in) throws IOException {
        return typeAdapter.fromJson(in);
    }

    // 从 JsonElement 解析对象
    public T fromJsonTree(JsonElement jsonTree) {
        return typeAdapter.fromJsonTree(jsonTree);
    }


    // 使用 JsonReader 读取对象
    public T read(JsonReader in) throws IOException {
        return typeAdapter.read(in);
    }

    // 将对象转换为 JSON 字符串
    public String toJson(T value) throws IOException {
        StringWriter writer = new StringWriter();
        toJson(writer, value);
        return writer.toString();
    }

    // 将对象写入 JSON Writer
    public void toJson(Writer out, T value) throws IOException {
        typeAdapter.toJson(out, value);
    }

    // 将对象转换为 JsonElement
    public JsonElement toJsonTree(T value) {
        return typeAdapter.toJsonTree(value);
    }

}
